package rule

import (
	"barge/app"
	"barge/pkg/manager"
	"barge/pkg/uix"
	"fmt"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"strings"
)

// setCmd represents the base command when called without any subcommands
var setCmd = &cobra.Command{
	Use:   "set",
	Short: "设置规则信息",
	Long:  fmt.Sprintf("支持配置以下规则: \n\t%v", strings.Join(manager.ActionInfoManager.ActionBriefs(), "\n\t")),
	Args: func(cmd *cobra.Command, args []string) error {
		if rule.Name == "" && len(args) > 0 {
			rule.Name = args[0]
		}

		if viper.GetBool("interactive") {
			if rule.Name == "" {
				rule.Name = uix.Input("请输入规则名称：")
			}
			if !cmd.Flag("action").Changed {
				briefs := manager.ActionInfoManager.ActionBriefs()
				i, err := uix.Select("请输入规则动作：", briefs)
				if err != nil {
					return err
				}
				brief := briefs[i]
				if brief != "" {
					rule.Action = manager.ActionInfoManager.GetActionNameByBrief(brief)
				}
			}
			if rule.Action == "" {
				return errors.New("action不能为空")
			}
			rule.Comment = manager.ActionInfoManager.GetActionInfo(rule.Action).Discript
			rule.Type = manager.ActionInfoManager.GetActionInfo(rule.Action).Type
			if rule.Action == manager.ActionReplace && rule.Source == "" {
				rule.Source = uix.Input("请输入源仓库：")
			}
			if rule.Action == manager.ActionReplace && rule.Target == "" {
				rule.Target = uix.Input("请输入替换仓库：")
			}
			if rule.Action == manager.ActionReplace {
				rule.Comment = uix.InputWithDefault("请输入备注：", rule.Comment)
			}
		} else if rule.Name == "" {
			return cmd.Help()
		}

		if rule.Name == "" {
			return errors.New("name不能为空")
		}
		err := rule.Validate()
		if err != nil {
			return err
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		m, err := app.NewConfigManager(viper.GetString("configPath"))
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
		m.SetRule(rule)
		err = m.Save()
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
	},
}

var rule = new(app.RuleOption)

func init() {
	ruleCmd.AddCommand(setCmd)
	setCmd.Flags().StringVarP(&rule.Name, "name", "n", "", "规则名称")
	setCmd.Flags().StringVarP(&rule.Action, "action", "a", "replace", "规则动作")
	setCmd.Flags().StringVarP(&rule.Source, "source", "s", "", "源镜像仓库")
	setCmd.Flags().StringVarP(&rule.Target, "target", "t", "", "目标镜像仓库")
}
